<template>
	<s-layout id="layout" :title="'实名认证'" :navbar="normal" leftIconColor="#ffffff" :autoBack="false"
		:leftIcon="leftIcon" :bgColor="state.bgColor" :tabbarshow='false'
		:titleStyle="{ color: '#FFF', fontSize: '32rpx' }">
		<view id="app" :style="{ backgroundImage: `url( ${baseUrl}/uploads/uniapp_image/staff/szmmbg.png)` }">
			<view class="top">
				<view class="title">实名认证</view>
				<text>安全便捷，真实有效</text>
			</view>

			<view class="middle">
				<view class="pass-wrap">
					<view class="passwrap">
						<view class="idcard">请您使用有效身份证信息认证</view>
						<view class="content">
							<uni-forms ref="relRef" v-model="state.formData" :rules="state.rules"
								validateTrigger="bind">

								<!---身份证--->
								<view class="IDcard">
									<view class="item">
										<view class="subtitle color">示例：</view>
										<image class="exampleimg"
											:src="`${baseUrl}/uploads/uniapp_image/user/sfz02.png`"
											mode="scaleToFill" />
									</view>
									<view class="item">
										<view class="title color">头像面上传</view>
										<u-upload :deletable="!is_authentication" :fileList="state.fileList2" @afterRead="identityCardUpload"
											@delete="deletePic" name="2" multiple :maxCount="1">
											<image class="uploadimg"
												:src="`${baseUrl}/uploads/uniapp_image/user/xj.png`"
												mode="scaleToFill" />
										</u-upload>
									</view>
								</view>
								<view class="IDcard">
									<view class="item">
										<view class="subtitle color">示例：</view>
										<image class="exampleimg"
											:src="`${baseUrl}/uploads/uniapp_image/user/sfz01.png`"
											mode="scaleToFill" />
									</view>
									<view class="item">
										<view class="title color">国徽面上传</view>
										<u-upload :deletable="!is_authentication" :fileList="state.fileList1" @afterRead="identityCardUpload"
											@delete="deletePic" name="1" multiple :maxCount="1">
											<image class="uploadimg"
												:src="`${baseUrl}/uploads/uniapp_image/user/xj.png`" />
										</u-upload>
									</view>
								</view>

								<view v-if="state.formData.realName && state.formData.authority">
									<uni-forms-item name="realName" label="真实姓名">
										<uni-easyinput :disabled="true" placeholder="请输入真实姓名" v-model="state.formData.realName"
											:inputBorder="false">
										</uni-easyinput>
									</uni-forms-item>
									<uni-forms-item name="identityCard" label="证件号码">
										<uni-easyinput :disabled="true"  placeholder="请输入身份证号码" v-model="state.formData.identityCard"
											:inputBorder="false">
										</uni-easyinput>
									</uni-forms-item>
									<uni-forms-item name="sex" label="选择性别">
										<uni-data-select  :disabled="true"  v-model="state.formData.sex" placeholder="请选择性别"
											:localdata="state.formData.sexlist" @change="change"></uni-data-select>
									</uni-forms-item>
									<button class="submit" @tap="resetPasswordSubmit" v-if="!is_authentication"> 立即认证 </button>
								</view>

							</uni-forms>
						</view>
					</view>
					<!--提示信息-->
					<view class="hint">
						<view class="icon">
							<image :src="`${baseUrl}/uploads/uniapp_image/user/tanhao.png`" mode="scaleToFill" />
						</view>
						<view class="cont">实名仅用于您是否为真人用户，不会对信息做任何采集与保留，请放心使用</view>
					</view>
				</view>

			</view>
		</view>
	</s-layout>
</template>

<script setup>
import { baseUrl } from '@/sheep/config';
import sheep from '@/sheep';
import { ref, reactive, unref } from 'vue';
import { realName, identityCard, sex } from '@/sheep/validate/form';
import { onLoad } from '@dcloudio/uni-app';
const relRef = ref(null);
const is_authentication  = sheep.$store('user')?.userInfo.is_authentication
onLoad((options) => {
	// if(is_authentication) {
	// 	get_user_authenticationData()
	// }

	if(options) {
      share_options = options.share_options
    }
})
let share_options = {}

const state = reactive({
	fileList1: [],
	fileList2: [],
	formData: {
		realName: '',
		identityCard: '',
		sex: '',
		birthday:'',
		nation:'',
		address:'',
		authority:'',
		valid_date:'',
		idcardFront: '',
		idcardBack: '',
		sexlist: [
			{ value: 0, text: "女" },
			{ value: 1, text: "男" },
		]

	},
	rules: {
		realName,
		identityCard,
		sex
	},
});
// 封装获取用户实名认证信息
const get_user_authenticationData = async () => {
	const res = await sheep.$api.user.get_user_authenticationAPI()
	state.formData.realName = res.data.name
	state.formData.identityCard = res.data.identity_id
	state.formData.sex = Number(res.data.gender)
	state.fileList1 = ref([{
			url: `${baseUrl}`+res.data.reverses_image,
		}])
		state.fileList2 = ref([{
			url: `${baseUrl}`+res.data.front_image,
		}])
	
	
}
// 删除图片
const deletePic = (event) => {
	if(event.name == 2) {
		state.formData.identityCard = ''
		state.formData.realName = ''
		state.formData.sex = ''
		state.formData.birthday = ''
		state.formData.nation = ''
		state.formData.address = ''
	} else {
		state.formData.authority = ''
		state.formData.valid_date = ''
	}
	state[`fileList${event.name}`].splice(event.index, 1)
};

// 新增图片身份证
const identityCardUpload = async (event, e) => {
	// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	let lists = [].concat(event.file);
	let fileListLen = state[`fileList${event.name}`].length
	lists.map((item) => {
		state[`fileList${event.name}`].push({
			...item,
			status: 'uploading',
			message: '上传中',
		});
	});
	for (let i = 0; i < lists.length; i++) {
		const url = await uploadFilePromise(lists[i].url, event.name);
		let item = state[`fileList${event.name}`][fileListLen]
		state[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
			...item,
			status: 'success',
			message: '',
			url: sheep.$url.cdn(url),
		}))
		fileListLen++;
	}

	// if(event.name == 2) {
		ocrIdentify(lists[0].url)
		console.log(lists[0].url)
	// }
}


	// ocr识别功能
 function ocrIdentify(tempFilePath) {
	console.log(tempFilePath)
	uni.showLoading({
		title: '读取中'
	})
	const invokeRes =   wx.serviceMarket.invokeService({
		service: 'wx79ac3de8be320b71', // '固定为服务商OCR的appid，非小程序appid
		api: 'OcrAllInOne', //固定的不要动
		data: {
			// 用 CDN 方法标记要上传并转换成 HTTP URL 的文件
			img_url: new wx.serviceMarket.CDN({ 
				type: 'filePath',
				filePath: tempFilePath,
			}),
			data_type: 3,
			ocr_type: 1 // 1是身份证识别  7是营业执照识别
		},
		success: function(res) { //打印这个res  就是你想要的结果
			if(res.errMsg == 'invokeService:ok') {
				if(res.data.idcard_res.type ==  0) {
					state.formData.identityCard = res.data.idcard_res.id.text
					state.formData.realName = res.data.idcard_res.name.text
					state.formData.sex = res.data.idcard_res.gender.text == '男'?1:0
					state.formData.birthday = res.data.idcard_res.birth.text
					state.formData.nation = res.data.idcard_res.nationality.text
					state.formData.address = res.data.idcard_res.address.text
				} else {
					state.formData.authority = res.data.idcard_res.authority.text
					state.formData.valid_date = res.data.idcard_res.valid_date.text
				}
			}
			uni.hideLoading()
		},
		fail: function (err) {
			console.log(err)
			sheep.$helper.toast('请上传有效且真实的身份证')
		}
	})
}
const uploadFilePromise = async (tempUrl, event) => {
	let { url } = await sheep.$api.app.upload(tempUrl, 'ugc');
	if (event == 1) {
		state.formData.idcardBack = url
	}
	if (event == 2) {
		state.formData.idcardFront = url
	}
	return url;
};
// 数据
function change(e) {
	// console.log("e:", e);
}




const bgColor = ref('transparent')
// 4.实名认证
const resetPasswordSubmit = async () => {
	const validate = await unref(relRef)
		.validate()
		.catch((error) => {
		});
	if (!validate) return;
	if (state.fileList1 == '') {
		sheep.$helper.toast('请上传身份证正面');
		return false
	}
	if (state.fileList2 == '') {
		sheep.$helper.toast('请上传身份证反面');
		return false
	}

	let p = {
		name: state.formData.realName,
		identity_id: state.formData.identityCard,
		gender: state.formData.sex,
		birthday:state.formData.birthday, // 生日
		nation:state.formData.nation, // 民族
		address:state.formData.address,
		authority:state.formData.authority,
		valid_date:state.formData.valid_date,
		front_image: state.formData.idcardFront,
		reverses_image: state.formData.idcardBack
	}

	sheep.$api.user.account.username(p).then(res => {
		sheep.$helper.toast(res.msg);
		if (res.code == 1) {
			// setTimeout(() => {
				sheep.$store('user').getInfo();
			// }, 500)
			setTimeout(() => {
				sheep.$router.back()
				uni.$emit('sharingParameter',share_options)
			}, 1000)
		}
	});
};

</script>

<style lang="scss">
@import '../auth/components/login.scss';

#app {
	// padding-bottom: 60rpx;
	height: 100vh;
	overflow: hidden;
}

.top {
	height: 398rpx;
}

.middle {
height: auto;
	background: transparent;
	.pass-wrap{
		height: calc(100vh - 398rpx);
	
	overflow-y: auto;
	}
	:deep(.uni-forms-item.is-direction-left) {
		flex-direction: row;
		text-align: center;
		margin-bottom: 44rpx !important;

		.uni-forms-item__label {
			border-radius: 50rpx 0 0 50rpx;
			background-color: #F4F6FA;
			width: 180rpx !important;
			height: 90rpx !important;
			line-height: 90rpx !important;
			font-size: 26rpx !important;

			text {
				width: 100%;
				text-align: center;
			}
		}

		.uni-easyinput__content-input {
			border-radius: 0 50rpx 50rpx 0;
			color: #2979ff;
		}

		.uni-stat-box {
			height: 90rpx !important;
			line-height: 90rpx !important;
			text-align: left;
			border-radius: 0 50rpx 50rpx 0;
			background-color: #F4F6FA;
			font-size: 26rpx;

			.uni-select {
				height: 90rpx;
				padding-right: 20rpx;
				border-radius: 0 50rpx 50rpx 0 !important;
			}

			.uni-select__input-placeholder {
				color: #cecece !important;
			}
		}

		.uni-stat__actived {
			background-color: transparent;

			.uniui-clear {
				color: #2979ff;
			}

			.uni-select {
				height: 90rpx !important;
				padding-left: 0;
				
				.uni-select__input-text {
					border-radius: 0 50rpx 50rpx 0;
					padding-left: 20rpx;
					background: #F4F6FA;
				}
			}

			.uni-select__input-text {
				color: #2979ff;
			}
		}

		.uni-select {
			border: none;

		}
	}

	.content {
		margin: 26rpx auto;
	}
}

// 使用身份证信息
.passwrap {
	width: 94%;
	border-radius: 20rpx;
	box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.05);
	background: $uni-bg-color;
	// height: 56%;
	margin: 0 auto;

	.idcard {
		border-radius: 20rpx 20rpx 0 0;
		height: 104rpx;
		line-height: 104rpx;
		padding-left: 40rpx;
		font-family: PingFangSC;
		color: $uni-text-color;
		font-weight: $uni-font-weight;
		font-size: $uni-font-size-big;
		background: #F4F6FA;
	}
}

:deep(.u-icon__icon) {
	background: #3333336e;
	width: 64rpx;
	height: 64rpx;
	justify-content: center;
	border-radius: 50%;
}

//提示消息
.hint {
	width: 94%;
	border-radius: 20rpx;
	box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.05);
	background: $uni-bg-color;
	height: 11%;
	margin: 24rpx auto;
	display: flex;
	padding: 20rpx 0;

	.icon {
		padding-left: 4%;
		padding-top: 2%;

		image {
			width: 32rpx;
			height: 32rpx;
		}
	}

	.cont {
		font-family: PingFangSC;
		padding: 0 4%;
		color: #424242;
		font-weight: 500;
		font-size: 26rpx;
		line-height: 45rpx;
	}
}

// 身份证照片
.IDcard {
	width: 100%;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 2rpx solid #F4F6FA;
	padding-bottom: 30rpx;

	.item {
		width: 48%;

		:deep(.u-upload) {
			width: 100%;
			height: 200rpx;
			border: 2rpx solid $uni-color-primary;
			overflow: hidden;
			border-radius: 16rpx;

			.u-upload__wrap {
				flex-wrap: inherit;
				justify-content: center;
				align-items: center;
			}

			.uploadimg {
				width: 108rpx;
				height: 108rpx;
			}
		}
	}

	.title {
		color: #424242;
	}

	.color {
		font-family: PingFangSC;
		font-weight: 500;
		font-size: $uni-font-size-base;
		margin: 30rpx 0 30rpx 0;
	}

	.subtitle {
		color: #AAAAAA;
	}

	.exampleimg {
		width: 100%;
		height: 200rpx;
	}

}

.content {
	padding-bottom: 40rpx;

	.submit {
		width: 60%;
		margin: 60rpx auto 0 auto;

	}
}

:deep(.u-upload__wrap__preview) {
	width: 304rpx;
	height: 200rpx;
	margin: 0 !important;

	image {
		width: 100% !important;
		height: 100% !important;
	}

	.u-upload__deletable {
		background-color: transparent !important;
	}

	.u-upload__success {
		border: transparent !important;
	}

	.u-upload__success__icon {
		bottom: 0px;
		right: 0px;
	}

}

::-webkit-scrollbar {
	display: none;
}
:deep(.is-disabled){
	border-radius: 0 50rpx 50rpx 0;
}
:deep(.uni-stat__select){
	.uni-stat__actived{
		.uni-select--disabled{
			border-radius: 0 50rpx 50rpx 0;
		}
	}

}
</style>